#!/usr/bin/python2
# -*- coding: UTF-8 -*-

import logging
import urllib
import sys
import os
import re
import json
import codecs
import copy
import threading
import importlib
import douding
import baidu

importlib.reload(sys)
sys.path.append('../')

from base import utils
# sys.setdefaultencoding("utf-8")

class DoudingService(threading.Thread):
    config_file = "../config/downdoc.json"
    config = {}

    def __init__(self):
        utils.logConf(True, "downdoc-" + utils.getSysTime() + ".log")
        threading.Thread.__init__(self)
        pass

    def __del__(self):
        pass

    def startup(self):
        if not self.read_conf():
            logging.error("read config %s failed" % self.config_file)
            return False
        self.start()
        return True

    def run(self):
        urls = self.config['urls']
        for url in urls:
            self.process(url)
        pass

    def process(self, url):
        try:
            domain = utils.parse_domain(url)
            if domain:
                for item in self.config['domains']:
                    # 匹配域名
                    if domain != item[0]:
                        continue

                    # 检查开关
                    if item[2] != "on":
                        logging.error("url: '%s' don't support." % url)
                        break

                    # 选择下载器
                    if item[1] == "baidu":
                        baidu.download(url)
                    elif item[1] == "douding":
                        douding.download(url)
                    else:
                        logging.error("url: '%s' don't support." % url)

                    break
            else:
                logging.error("url: '%s' don't support." % url)
        except Exception as error:
            logging.error(error)

    def read_conf(self):
        if not os.path.exists(self.config_file):
            logging.error("don't exist config file " + self.config_file)
            return False

        config_file = open(self.config_file, "r")
        content = config_file.read()

        try:
            self.config = json.loads(content)
        except Exception as e:
            logging.error("read config file:'%s' failed: %s" % (self.config_file, e))
            return False
        return True

if __name__ == '__main__':
    urls = [
        "https://wenku.baidu.com/view/443fa25c804d2b160b4ec01f.html?sxts=1525673013039"
        #"http://www.docin.com/p-1400892147.html"
    ]

    service = DoudingService()
    service.read_conf()
    for url in urls:
        service.process(url)
else:
    pass